在android中启动手机启动活动

Ron*_*hta 2 android

我试图在手机启动时开始活动但整个程序没有运行程序中没有错误,请看我的编码(或http://pastebin.com/BKaE4AaU):

autostart.java

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.content.SharedPreferences;  
import android.preference.PreferenceManager;  
import android.util.Log;


public class autostart extends BroadcastReceiver 
{
    public void onReceive(Context arg0, Intent arg1) 
    {
        Intent intent = new Intent(arg0,service.class);
        arg0.startService(intent);
        Log.i("Autostart", "started");
    }
}
Run Code Online (Sandbox Code Playgroud)

service.java

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class service extends Service
{
    private static final String TAG = "MyService";
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onStart(Intent intent, int startid)
    {
        Intent intents = new Intent(getBaseContext(),hello.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}
Run Code Online (Sandbox Code Playgroud)

hello.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class hello extends Activity 
{   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

manifest.java如下

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver  android:name=".autostart"
              android:label="@string/app_name">
        <intent-filter>
              <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
Run Code Online (Sandbox Code Playgroud)

Fra*_*per 5

您的XML应存储在名为AndroidManifest.xml的文件中,而不是manifest.java中.

您的代码未运行的另一个原因可能是您的应用程序安装在外部存储(SD卡)上.在挂载外部存储之前,BOOT_COMPLETE将发送到应用程序.因此,如果应用程序安装到外部存储器,它将不会收到BOOT_COMPLETE广播消息.

如果这不是问题,那么已经非常好地描述了如何在Android上启动已启动的接收器.