重启电话时调用功能

时间:2015-05-13 07:11:39

标签: android

我想在手机重启时调用一个功能。我正在启动服务,但无法调用另一个类的功能。请帮帮我。

我使用以下代码解决此问题:

广播接收器:

public class BootComplete extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { 
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AutoStartUp.class);
            context.startService(serviceIntent);
        }
    }
}

服务

public class AutoStartUp extends Service {
    MainActivity mainActivity;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        mainActivity.abc();
    }
}

主要活动:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "Welcome1", Toast.LENGTH_LONG).show();
        abc();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void abc() {
        Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show();
    }
}

清单:

    <receiver
        android:name=".BootComplete"
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

    <service android:name=".AutoStartUp" >
    </service>

    <activity
        android:name="com.example.androidautostartup.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

我使用上面的代码但仍无法解决问题。

2 个答案:

答案 0 :(得分:0)

你的代码没有意义:

  

MainActivity mainActivity;

在您的服务中,它是如何初始化的?现在看起来它是null所以:

  

mainActivity.abc();

导致NullPointerException。

通常,当您想要将某些信息从服务返回到Activity时,您可以使用本地广播。

答案 1 :(得分:0)

您无法直接从Activity调用Service的方法。用于例如ServiceActivity Android提供BroadcastReceiver。以下tutorial是一个良好的开端。

简而言之,您可以使用BroadcastReceiverService发送命令Activity,如下所示:

服务方:

[...]
private void sendMessage() {
  Intent intent = new Intent("myEventCommunicator");
  intent.putExtra("message", "abc");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
[...]

活动方:

[...]
@Override
public void onResume() {
  super.onResume();

  // Register handler to receive messages.
  LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver,
      new IntentFilter("myEventCommunicator"));
}

// Create handler for receiving messages
private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get data from message and do desired stuff
    String message = intent.getStringExtra("message");
    Log.d("Received message", "Message content: " + message);
    if(message.equals("abc") {
        abc();
    }
  }
};

private void abc() {
   // do some abc stuff...
}

@Override
protected void onPause() {
  // Unregister when app becomes paused
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onPause();
}
[...]

您还可以从Activity开始/恢复Service这样的 Intent i = new Intent(); i.setClass(service.getBaseContext(), MyActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra("id", id + ""); context.startActivity(i);

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/sfondo_semi_trasparente_scuro">




<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@color/white"
    android:orientation="vertical">





    <EditText
        android:id="@+id/textNomeGiocatoreNewTeam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Nome giocatore"/>


    <EditText
        android:id="@+id/textNumeroMagliaGiocatoreNewTeam"
        android:inputType="number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Numero Maglia"/>

    <Button
        android:id="@+id/buttonConfirmAddNewPlayer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Aggiungi giocatore"
        android:layout_gravity="center"/>


</LinearLayout>

您的应用程序应位于launchMode = singleTop 中,以便将隐藏的实例(如果存在)带到前面,或者如果不存在旧实例则启动新实例。