简体   繁体   English

Android小部件启动应用程序并检测未找到的应用程序

[英]Android widget launch App and detect App Not found

I need a simple home Widget to launch an external app (ex: whatsapp). 我需要一个简单的家庭小部件来启动外部应用程序(例如:whatsapp)。

In my MainActivity extends AppWidgetProvider (onUpdate) I use this code to create a pending intent and work great if the App is installed. 在我的MainActivity扩展AppWidgetProvider(onUpdate)中,我使用此代码创建挂起的意图,如果安装了该应用程序,则效果很好。

Intent intent = new Intent();
ComponentName cn = new ComponentName("com.whatsapp", "com.whatsapp.Main");
intent.setComponent(cn);

PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
views.setOnClickPendingIntent(R.id.imageView, pending);

appWidgetManager.updateAppWidget(currentWidgetId, views);

In the (onReceive) section i use this code for detect if the App is installed 在(onReceive)部分中,我使用此代码来检测是否已安装该应用程序

 PackageManager pm = context.getPackageManager();

        List<ApplicationInfo> list = pm.getInstalledApplications(0);

        for (int aa = 0; aa < list.size(); aa++) {         
            if(list.get(aa).packageName.equals("com.whatsapp")){  
                 //app istalled
                noapp = 0;
            }
            else{
                //app not istalled
                noapp1 = 1;         
            }
        }         
    if(noapp1==1){
    Toast.makeText(context, "Whatsapp not installed", Toast.LENGTH_SHORT).show();
  }

My problem is: This code detect if the App is not installed and display the Toast message but only the first time the widget is positioned in the home. 我的问题是:此代码检测是否未安装该应用程序,并仅在第一次将小部件放置在家庭中时显示Toast消息。 I need to display the message any time the imageview is touched if the App is not installed. 如果未安装该应用程序,则每当触摸imageview时,我都需要显示该消息。 Please Help! 请帮忙!

Karakuri I try to apply your suggestion. 卡拉库里,我尝试应用您的建议。 This is my code in the main activity for attach the intent to the imageView: 这是我将意图附加到imageView的主要活动中的代码:

public class MainActivity extends AppWidgetProvider{

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    for(int i=0; i<appWidgetIds.length; i++){
        int currentWidgetId = appWidgetIds[i];

        Intent intent = new Intent(LaunchExternalAppReceiver.ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
        views.setOnClickPendingIntent(R.id.imageView, pendingIntent); 
        // Tell the AppWidgetManager to perform an update on the current App Widget
        appWidgetManager.updateAppWidget(currentWidgetId, views);

    }      
  }   
}

And this the new class with BroadcastReceiver (I put inside my simpele code to check if the App is installed, just for test): 这是带有BroadcastReceiver的新类(我将我的简单代码放入其中以检查是否已安装该应用程序,仅用于测试):

public class LaunchExternalAppReceiver extends BroadcastReceiver {
public static final String ACTION = "control";

@Override
public void onReceive(Context context, Intent intent) {

    PackageManager pm = context.getPackageManager();

    List<ApplicationInfo> list = pm.getInstalledApplications(0);

    for (int aa = 0; aa < list.size(); aa++) {  

        if(list.get(aa).packageName.equals("com.whatsapp")){  
            //app istalled

        }
        else{
            //app not istalled             
            Toast.makeText(context, "Whatsapp not installed", Toast.LENGTH_SHORT).show();
        }
    }             
  }
}

This is my Manifest: 这是我的清单:

 <uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" /><application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <receiver android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/mywidget" />
    </receiver>
    <receiver android:name=".LaunchExternalAppReceiver" >
        <intent-filter>
            <action android:name="control" >
            </action>
        </intent-filter>
    </receiver>
</application>

Thanks a lot for your help. 非常感谢你的帮助。

Have the ImageView click send a broadcast to a receiver in your app (using PendingIntent.getBroadcast() ). 让ImageView单击将广播发送到应用程序中的接收者(使用PendingIntent.getBroadcast() )。 In that receiver you can check if the external app is installed and launch it from there. 在该接收器中,您可以检查是否安装了外部应用程序并从那里启动它。

EDIT 编辑

Make a new BroadcastReceiver. 制作一个新的BroadcastReceiver。

public class LaunchExternalAppReceiver extends BroadcastRecevier {
    public static final String ACTION = "some-unique-string-here";

    @Override
    public void onReceive(Context context, Intent intent) {
        // check if the external app is installed and launch it
        PackageManager pm = context.getPackageManager();
        try {
            pm.getApplicationInfo("com.whatsapp", 0); // throws if not found
            Intent intent = pm.getLaunchIntentForPackage("com.whatsapp");
            if (intent != null) {
                context.startActivity(intent);
            }
        } catch (NameNotFoundException e) {
            // package not found, you can show the Toast here
        }
    }
}

Add it to your AndroidManifest. 将其添加到您的AndroidManifest。 Make sure the intent filter action matches the ACTION above. 确保意图过滤器动作与上面的动作匹配。

<receiver android:name=".LaunchExternalAppReceiver">
    <intent-filter>
        <action android:name="some-unique-string-here">
    </intent-filter>
</receiver>

Make your ImageView send a broadcast with this action instead of trying to launch the external app. 使您的ImageView通过此操作发送广播,而不是尝试启动外部应用程序。

Intent intent = new Intent(LaunchExternalAppReceiver.ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.imageView, pendingIntent);

I found an alternative solution. 我找到了替代解决方案。 Work greet but have an annoying little problem. 工作打招呼,但有一个烦人的小问题。 I attach an intent to the imageView in my main activity to launch a new class "control" in this class i check if the app is installed and launch her or send a message and offer a download button. 我在主要活动中将意向附加到imageView上,以在该类中启动新类“控件”,我检查应用程序是否已安装并启动她或发送消息并提供下载按钮。 The problem is...if the app is installed the control class launch her but for a second appear the activity (control) screen before App open. 问题是...如果安装了该应用程序,则控制类将启动她,但是在打开应用程序之前会出现第二个活动(控件)屏幕。 Very annoying. 很烦人。 Someone can help me to make this final fix? 有人可以帮助我做最后的修复吗? Thanks. 谢谢。

In onUpdate (main activity): 在onUpdate(主要活动)中:

    Intent controlIntent = new Intent(context, Control.class);          
    PendingIntent pendingc1 = PendingIntent.getActivity(context, 0, controlIntent, 0);
    RemoteViews views1 = new RemoteViews(context.getPackageName(), R.layout.activity_main);
    views1.setOnClickPendingIntent(R.id.imageView, pendingc1);
    appWidgetManager.updateAppWidget(currentWidgetId, views1); 

My new class (control): 我的新课程(控件):

public class Control extends Activity {
private TextView testo;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    PackageManager pm = this.getPackageManager();

    List<ApplicationInfo> list = pm.getInstalledApplications(0);

    for (int aa = 0; aa < list.size(); aa++) {

        if (list.get(aa).packageName.equals("com.whatsapp")) {
            // app istalled

            Intent launchIntent = getPackageManager()
                    .getLaunchIntentForPackage("com.whatsapp");
            startActivity(launchIntent);
            Control.this.finish();

        } else {
            setContentView(R.layout.control);
            // app not istalled
            testo = (TextView) findViewById(R.id.message);
            String text = "WhatsApp is Not Installed\nPlease Download Whatsapp from Play Store";
            testo.setText(text);

            Button button = (Button) findViewById(R.id.exit);
            button.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    Control.this.finish();
                }
            });

            Button button2 = (Button) findViewById(R.id.download);
            button2.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
                            .parse("market://details?id=" + "com.whatsapp")));
                    Control.this.finish();
                }
            });

        }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM