如何在android studio中打开应用程序之前获取通知

时间:2016-03-03 03:52:52

标签: java android

如何在打开应用程序之前获取通知或当我在移动设备上杀死应用程序仍然通知时显示。或者当我开始手机时我想通知但应用程序不应该运行。

public class BeaconService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showNotification();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
    private void showNotification() {
        NotificationCompat.Builder mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_loc)
                        .setContentTitle("Welcome to Brillio")
                        .setContentText("Hello Mansur, Welcome to Brillio.")
                        .setPriority(2)
                        .setOnlyAlertOnce(false);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(2001, mBuilder.build());
    }
}

BeaconReceiver.java

public class BeaconReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intentLunch = new Intent(context, BeaconService.class);
        context.startService(intentLunch);

    }
}

menifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <service
        android:name=".BeaconService"/>
        <receiver android:name=".BeaconReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>

1 个答案:

答案 0 :(得分:0)

在没有用户第一次打开应用程序的情况下,没有简单的方法可以在安装应用程序时启动服务。

您只需查看这两个链接了解更多信息

1)How to start a Service when .apk is Installed for the first time

2)How to start android service on installation

要制作预先通知的通知,请添加以下行:

builder.setOngoing(true)

希望这会对你有所帮助