2016-05-29 2 views
3

Возможно ли в текущем состоянии NativeScript создать приложение, которое прослушивает намерения для акций на Android?Могу ли я поделиться с моим NativeScript-приложением?

То, что я хотел бы получить, - это, например, открытие веб-сайта в моем браузере на Android, подключение к общему ресурсу и просмотр моего приложения NativeScript в списке целей общего доступа.

Я сделал это на родном приложении для Android, но не могу заставить его работать в приложении NativeScript. Я перепутал с AndroidManifest.xml, чтобы добавить

<action android:name="android.intent.action.SEND"></action> 
<category android:name="android.intent.category.DEFAULT"></category> 

в фильтр намерений, но это не помогло. Мое приложение не отображается в списке целей общего доступа.

ответ

1

NativeScript должен поддерживать этот сценарий из коробки. Вот что мой AndroidManifest в app/App_resources/Android неплатежа бутстрапированная приложение выглядит следующим образом:

<activity 
     android:name="com.tns.NativeScriptActivity" 
     android:label="@string/title_activity_kimera" 
     android:configChanges="keyboardHidden|orientation|screenSize"> 

     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
     <intent-filter> 
      <action android:name="android.intent.action.SEND" /> 
      <category android:name="android.intent.category.DEFAULT" /> 
      <data android:mimeType="text/plain" /> 
     </intent-filter> 
</activity> 

редактировать: Очень простая реализация отправить намерения любого из моего другого приложения:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent sendIntent = new Intent(Intent.ACTION_SEND); 
       sendIntent.setType("text/plain"); 
       sendIntent.putExtra("string", "the data Im sending you"); 

       Intent chooser = Intent.createChooser(sendIntent, "Share with "); 

       if (sendIntent.resolveActivity(getPackageManager()) != null) { 
        startActivity(chooser); 
       } 
      } 
     }); 
+0

Я, должно быть, что-то перепутал в своем коде, потому что он действительно работает с вашим примером. Я не уверен, как использовать этот фрагмент Java в моем проекте, но мне не нужно отправлять намерения из моего приложения. Спасибо @pkanev! – Najki

+0

Второй фрагмент кода - пример кода, демонстрирующий, как можно отправить намерение, которое вы можете использовать в приложении для Android, или получить доступ к собственному API Android через JavaScript в приложении NativeScript (http://docs.nativescript.org)./автономная работа/Android/генератор/расширение класса-интерфейс). – pkanev

2

В дополнение к intent- фильтр, который вы должны добавить в свой AppManifest.xml , убедитесь, что вы перестраиваете свое приложение (опция lifeync может не отражать изменения в AppManifest.xml)

Вот пример NativeScrip реализация т для основной доли

var app = require("application"); 

function onShare() { 

    var sharingIntent = new android.content.Intent(android.content.Intent.ACTION_SEND); 
    sharingIntent.setType("text/plain"); 
    var shareBody = "Here is the share content body"; 

    sharingIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 
    sharingIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK); 

    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here"); 
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); 

    app.android.context.startActivity(sharingIntent); 
} 
exports.onShare = onShare; 
+0

Спасибо @ nick-iliev :) – Najki

1

Первый обновить AndroidManifest.xml в приложение/App_Resources/AndroidManifest.xml

Добавить НАМЕРЕНИЙ-фильтр, как показано ниже

<application  android:name="com.tns.NativeScriptApplication"  android:allowBackup="true"  android:icon="@drawable/icon"  android:label="@string/app_name" 
       android:theme="@style/AppTheme">  <activity   android:name="com.tns.NativeScriptActivity" 
         android:label="@string/title_activity_kimera"   android:configChanges="keyboardHidden|orientation|screenSize"> 

         <intent-filter> 
       <action android:name="android.intent.action.MAIN" />         
       <category android:name="android.intent.category.LAUNCHER" />   </intent-filter>       
         <intent-filter> 
           <action android:name="android.intent.action.SEND" /> 
           <category android:name="android.intent.category.DEFAULT" /> 
           <category android:name="android.intent.category.APP_BROWSER" /> 
           <data android:mimeType="text/plain" /> 
           <data android:mimeType="image/*" /> 
         </intent-filter> 
         <intent-filter> 
          <action android:name="android.intent.action.SEND_MULTIPLE" /> 
          <category android:name="android.intent.category.DEFAULT" /> 
          <category android:name="android.intent.category.APP_BROWSER" /> 
          <data android:mimeType="image/*" /> 
         </intent-filter> 
           </activity>   <activity android:name="com.tns.ErrorReportActivity"/> </application> 

Затем добавить следующие строки кода в вашем app.js

application.android.on(application.AndroidApplication.activityResumedEvent, function (args) { 
     console.log("Event: " + args.eventName + ", Activity: " + args.activity); 
     var a = args.activity; 
     try { 
      var Intent_1 = android.content.Intent; 
      var actionSend = Intent_1.ACTION_SEND; 
      var actionSendMultiple = Intent_1.ACTION_SEND_MULTIPLE; 
      var argIntent = a.getIntent(); 
      var argIntentAction = argIntent.getAction(); 
      var argIntentType = argIntent.getType(); 
      console.log(" ~~~~ Intent is ~~~~ :" + new String(argIntent.getAction()).valueOf()); 
      String.prototype.startsWith = function (str) { 
       return this.substring(0, str.length) === str; 
      }; 
      if (new String(argIntentAction).valueOf() === new String(Intent_1.ACTION_SEND).valueOf()) { 
       if (new String(argIntentType).valueOf() === new String("text/plain").valueOf()) { 
        console.dump(cbParseTextAndUrl(argIntent)); 
       } 
       else if (argIntentType.startsWith("image/")) { 
        console.log(cbParseImageUrl(argIntent)); 
       } 
      } 
      else if (new String(argIntentAction).valueOf() === new String(Intent_1.ACTION_SEND_MULTIPLE).valueOf()) { 
       if (argIntentType.startsWith("image/")) { 
        var Uri = cbParseMultipleImageUrl(argIntent); 
        if (Uri !== null) { 
         var Uris = JSON.parse(Uri); 
         console.log(Uris); 
        } 
       } 
      } 
      function cbParseTextAndUrl(argIntent) { 
       var Patterns = android.util.Patterns; 
       //let Matcher = java.util.regex.Matcher; 
       var ListUrl = []; 
       var text = argIntent.getStringExtra(Intent_1.EXTRA_TEXT); 
       if (new String().valueOf() !== "null") { 
        var Matcher = Patterns.WEB_URL.matcher(text); 
        while (Matcher.find()) { 
         var url = Matcher.group(); 
         ListUrl.push(url); 
        } 
        return { "text": text, "listUrl": ListUrl }; 
       } 
      } 
      function cbParseImageUrl(argIntent) { 
       var imageUri = argIntent.getParcelableExtra(Intent_1.EXTRA_STREAM); 
       if (imageUri != null) { 
        // Update UI to reflect image being shared 
        return imageUri; 
       } 
      } 
      function cbParseMultipleImageUrl(argIntent) { 
       var imageUris = argIntent.getParcelableArrayListExtra(Intent_1.EXTRA_STREAM); 
       if (imageUris != null) { 
        // Update UI to reflect image being shared 
        return JSON.stringify(imageUris.toString()); 
       } 
      } 
     } 
     catch (e) { 
      console.log(e); 
     } 
    }); 

Теперь вы можете поделиться своим конт от стороннего приложения к вашему приложению.

Смежные вопросы